package com.webdemo.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.webdemo.dal.model.Users;
import com.webdemo.service.user.impl.UserServiceImpl;
import com.webdemo.util.exception.SessionTimeoutException;

@Controller
public class LoginController {
	
	@Resource
	private UserServiceImpl userServiceImpl;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String indexS(HttpServletRequest request,
			HttpServletResponse response,HttpSession session) {
		//保存来源地址
		String srcUrl = request.getHeader("referer");
		session.setAttribute("sourceUrl", srcUrl);
		System.out.println(srcUrl);
		return "login";
	}
	@RequestMapping(value = "submit", method = RequestMethod.POST)
	public String submit(HttpSession session,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SessionTimeoutException {
		Users u = new Users();
		List<Users> userList = null;
		List<Map<String,Object>> lh = null;
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if(username!=null&&!username.equals("")&&
				password!=null&&!password.equals("")){
			u.setUsername(username);
			u.setPassword(password);
			//String sql = "select userId, username, password from users WHERE 1 = 1 and username = "+username+" and password='"+password+"'";
			//lh = jdbcTemplate.queryForList(sql);
			userList = userServiceImpl.selectByParam(u);
		}
		if(userList==null||userList.size()<=0){
			throw new SessionTimeoutException("登录出错!");
		}
		session.setAttribute("user", u);
		//跳转到来源页面
		String sourceUrl = (String)session.getAttribute("sourceUrl");
		if(sourceUrl!=null&&sourceUrl.startsWith("http://")){
			//过滤前缀
			String pex = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
			sourceUrl = sourceUrl.replace(pex, "");
			if(sourceUrl!=null&&!sourceUrl.trim().equals("")
					&&!sourceUrl.trim().equals("submit")
					&&!sourceUrl.trim().equals("login")){
				return "redirect:"+sourceUrl;	
			}
		}
		return "redirect:index";
	}
}
